import { useEffect, useState } from "react";
import { Select, Input } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import Highlighter from "react-highlight-words";
import { getStaffs } from "@/assets/js/networkRequest/method";

interface SelectStaffProps {
  id: string;
  width?: number;
  placeholder: string; // 提示信息
  multiple?: boolean; // 是否多选
  value?: any; // 默认值
  setStaff: any; // 设置员工信息
}

const { Option } = Select;

// 全部用户
let totalUserList: any = [];
// 当前可选择的用户
let userList: any = [];

let requesting: boolean = true;
let current: number = 1;
let pageCount: number = 0;

const SelectStaff = ({
  id,
  placeholder,
  value = "",
  multiple = false,
  setStaff,
}: SelectStaffProps) => {
  let [serchKey, setSerchKey] = useState("");
  const [, setRender] = useState(0);

  // 根据当前页请求列表数据请求
  const requestListData = async () => {
    requesting = true;
    let res: any = await getStaffs({ current, limit: 50, follow_user: 1 });
    if (res.code === 200) {
      requesting = false;
      let { data } = res;
      pageCount = data.pageCount;
      let newlist = [...totalUserList, ...data.list];
      userList = newlist;
      totalUserList = JSON.parse(JSON.stringify(newlist));
      setRender(Math.random() + 1);
    }
  };

  // 名称搜索
  const serchUser = () => {
    if (!serchKey) {
      userList = JSON.parse(JSON.stringify(totalUserList));
    } else {
      userList = totalUserList.filter(
        (item: any) =>
          item.name.indexOf(serchKey) !== -1 || item.alias.indexOf(serchKey) !== -1
      );
    }
    // console.log(userList);
    setRender(Math.random() + 1);
  };

  useEffect(() => {
    totalUserList = [];
    requestListData();
  }, [id]);

  const props: any = {};
  if (!multiple) {
    props.defaultValue = value || null;
  } else {
    props.mode = "multiple";
    props.maxTagCount = 2;
  }

  return (
    <div id={id} className="flex items-center">
      {userList.length > 0 && (
        <Select
          allowClear
          placeholder={placeholder}
          style={{ width: 300 }}
          virtual={false}
          {...props}
          getPopupContainer={(): any => document.getElementById(id)}
          onChange={(value: any) => {
            let staff = userList.filter((item: any) => value.indexOf(item.uid) !== -1);
            setStaff(staff);
          }}
          dropdownRender={menu => (
            <div className="group-list">
              <p className="mb-10 mt-20 pl-20">全部成员（{userList.length}）</p>
              <div className="px-20 pb-10">
                <Input
                  prefix={
                    <SearchOutlined style={{ color: "#D3D3D3" }} onClick={serchUser} />
                  }
                  placeholder="请输入成员昵称,回车搜索"
                  width={263}
                  onPressEnter={(e: any) => {
                    serchUser();
                    e.stopPropagation();
                  }}
                  onChange={(e: any) => {
                    setSerchKey(e.target.value.trim());
                    if (!e.target.value) {
                      serchKey = "";
                      serchUser();
                    }
                  }}
                />
              </div>
              <div
                className="max-h-250 scrollY menu"
                onScroll={(event: any) => {
                  /* 距离顶部100px，总页码大于当前页面，当前页面不是第一页，上次滚动请求完后 */
                  let scrollBottom =
                    event.target.scrollHeight -
                    event.target.scrollTop -
                    event.target.clientHeight;
                  if (scrollBottom < 10 && current < pageCount && !requesting) {
                    current += 1;
                    requestListData();
                  }
                }}>
                {menu}
              </div>
            </div>
          )}>
          {/* 备用员工列表 */}
          {userList.map((item: any) => {
            return (
              <Option key={item.uid} value={item.uid}>
                <div className="avatar-and-name flex items-center">
                  <img alt="" src={item.avatar} className="rounded-2 mr-10 w-36 h-36" />
                  <div className="name flex flex-col p-0 items-start">
                    <span data-memberextid="YuShiKang">
                      <Highlighter
                        highlightStyle={{ color: "#1890ff" }}
                        searchWords={[serchKey]}
                        autoEscape
                        textToHighlight={item.name}
                      />
                    </span>
                    {serchKey && item.alias.indexOf(serchKey) !== -1 ? (
                      <span className="alias text-xs text-grey-300">
                        别名：
                        <span>
                          <Highlighter
                            highlightStyle={{
                              color: "#1890ff",
                            }}
                            searchWords={[serchKey]}
                            autoEscape
                            textToHighlight={item.alias}
                          />
                        </span>
                      </span>
                    ) : null}
                  </div>
                </div>
              </Option>
            );
          })}
        </Select>
      )}
    </div>
  );
};

export default SelectStaff;
